//
//  ProductOperationController.m
//  FactorySale
//
//  Created by 胡小康 on 2020/4/21.
//  Copyright © 2020 主事丫环. All rights reserved.
//

#import "ProductOperationController.h"
#import "ProductOperationCell.h"
#import "ProductOperationSectionHeaderView.h"// 区头
#import "HistoryNumberController.h"// 历史申请数量控制器
#import "ApplicationSuccessfulController.h"
@interface ProductOperationController ()<UIGestureRecognizerDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic,strong) NSMutableArray <CooperationProductModel *>*productModelArray;// 区头数组
@property (nonatomic,strong) NSMutableArray *isExpandArray;// 存储展开闭合状态的数组
@property (nonatomic,strong) NSMutableArray *sectionDataArray;
@property (nonatomic,strong) NSString *numberStr;
@end

@implementation ProductOperationController
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    [self requestCooperationProductDataList];
}
- (void)setupUI{
    self.title = @"申请产品候保二维码";
    [self.leftbutton setImage:imgname(@"left_icon") forState:(UIControlStateNormal)];
    self.view.backgroundColor = Main_BackGroundColor;
    
    self.tableView.rowHeight = 130;
    self.tableView.tableFooterView = [[UIView alloc] init];
    
    self.productModelArray = [NSMutableArray arrayWithCapacity:0];
    self.isExpandArray = [NSMutableArray arrayWithCapacity:0];
    self.numberStr = @"";
    
}
- (void)requestCooperationProductDataList{
    
    self.sectionDataArray = [NSMutableArray arrayWithCapacity:0];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [NetWorkTool POST:getFactoryParts param:nil success:^(id dic) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        NSLog(@"%@",dic);
        //所有产品种类
        self.productModelArray = [CooperationProductModel mj_objectArrayWithKeyValuesArray:dic[@"data"]];
        
        NSArray * dataArray = dic[@"data"];
        for (int i = 0; i <dataArray.count; i++) {
            NSDictionary * listDic = dataArray[i];
            NSArray *attributeListArray = listDic[@"attrubites"];
            NSMutableArray *rowModelArray = [CooperationPriductListModel mj_objectArrayWithKeyValuesArray:attributeListArray];
            
            for (int j = 0; j<rowModelArray.count; j++) {
                CooperationPriductListModel *model = rowModelArray[j];
                model.count = @"";
            }
            
            [self.sectionDataArray addObject:rowModelArray];
            
        }
        
        for (int i = 0; i<self.productModelArray.count; i++) {
            [self.isExpandArray addObject:@"0"];//0:没展开 1:展开
        }
        [self.tableView reloadData];
        
    } other:^(id dic) {
        ShowToastWithText(dic[@"msg"]);
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    } fail:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    } needUser:YES];
    
}
#pragma mark -- UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return 50;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    ProductOperationSectionHeaderView * headerView = [[ProductOperationSectionHeaderView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 50)];
    headerView.sectionTitleLabel.text = self.productModelArray[section].parts_name;
    if ([_isExpandArray[section] isEqualToString:@"0"]) {
        //未展开
        headerView.arrowImageView.image = [UIImage imageNamed:@"向下"];
    }else{
        //展开
        headerView.arrowImageView.image = [UIImage imageNamed:@"向上"];
    }
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
    tap.delegate = self;
    [headerView addGestureRecognizer:tap];
    headerView.tag = section;
    
    return headerView;
}
- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    UIView * view = [[UIView alloc] init];
    view.backgroundColor = Main_BackGroundColor;
    return view;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 5;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    CooperationPriductListModel *model = self.sectionDataArray[indexPath.section][indexPath.row];
    // 跳转历史申请数量界面
    HistoryNumberController *vc = [[HistoryNumberController alloc] init];
    vc.id = model.id;
    [self.navigationController pushViewController:vc animated:YES];
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return self.productModelArray.count;
}
#pragma mark -- UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if ([self.isExpandArray[section]isEqualToString:@"1"]) {
        return self.productModelArray[section].attrubites.count;
    }else{
        return 0;
    }
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CooperationPriductListModel *model = self.sectionDataArray[indexPath.section][indexPath.row];
    ProductOperationCell *cell = [ProductOperationCell cellWithTableView:tableView];
    cell.model = model;
    cell.countChangedClick = ^(NSString * _Nonnull text) {
        model.count = text;
    };
    [cell.confirmButton addTarget:self action:@selector(confirmButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
    
}
/**
 *配件厂申请二维码请求
 */
- (void)confirmButtonClick:(UIButton *)sender{
    
    ProductOperationCell *productCell = (ProductOperationCell *)[[sender superview]superview];
    NSIndexPath *indexPathForCell = [self.tableView indexPathForCell:productCell];
    NSArray *rowModelArray = self.sectionDataArray[indexPathForCell.section];
    CooperationPriductListModel *model = rowModelArray[indexPathForCell.row];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"partsId"] = model.partsId;
    param[@"attribute"] = model.id;
    param[@"num"] = model.count;
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [NetWorkTool POST:batchQRCode param:param success:^(id dic) {

        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        params[@"realPath"] = dic[@"data"][@"realPath"];
        params[@"partsId"] = dic[@"data"][@"partsId"];
        [NetWorkTool POST:appPartsQrcode param:params success:^(id dic) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            NSString * email = dic[@"data"];
            ApplicationSuccessfulController * vc = [[ApplicationSuccessfulController alloc] init];
            vc.emailStr = email;
            [self presentViewController:vc animated:YES completion:nil];
        } other:^(id dic) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        } fail:^(NSError *error) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        } needUser:YES];
        
        NSDecimalNumber *totalCount = [NSDecimalNumber decimalNumberWithString:@"0"];
        NSDecimalNumber *appCount = [NSDecimalNumber decimalNumberWithString:model.appCount];
        NSDecimalNumber *count = [NSDecimalNumber decimalNumberWithString:model.count];
        
        totalCount = [appCount decimalNumberByAdding:count];
        model.appCount = [NSString stringWithFormat:@"%@",totalCount];
        productCell.numberTextField.text = @"";
        model.count = @"";
        [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:[NSIndexPath indexPathForRow:indexPathForCell.row inSection:indexPathForCell.section], nil] withRowAnimation:UITableViewRowAnimationNone];
        
    } other:^(id dic) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        ShowToastWithText(dic[@"msg"]);
        
    } fail:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    } needUser:YES];
}
- (void)tapAction:(UITapGestureRecognizer *)tap{
    if ([_isExpandArray[tap.view.tag] isEqualToString:@"0"]) {
        //关闭 => 展开
        
        [_isExpandArray replaceObjectAtIndex:tap.view.tag withObject:@"1"];
    }else{
        //展开 => 关闭
        
        [_isExpandArray replaceObjectAtIndex:tap.view.tag withObject:@"0"];
        
    }
    NSIndexSet *set = [NSIndexSet indexSetWithIndex:tap.view.tag];
    [self.tableView reloadSections:set withRowAnimation:UITableViewRowAnimationFade];

}
@end
